package com.xbb.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xbb.entity.Module;
import com.xbb.entity.Rolemodules;
import com.xbb.service.IRolemodulesService;
import com.xbb.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Mr xie
 * @since 2020-05-20
 */
@RestController
@RequestMapping("/rolemodules")
public class RolemodulesController {

    @Autowired
    IRolemodulesService iRolemodulesService;

    /**
     *给角色设置选中的模块
     * @param rid 角色的id
     * @param mids 模块id组成的字符串
     * @return
     */
    @PostMapping("/setModuleTreeByRoleId")
    public Object setModuleTreeByRoleId(@RequestParam Integer rid, @RequestParam String mids) {
        //1.批量删除指定的角色所有数据（中间表）
        QueryWrapper<Rolemodules>  queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",rid);
        iRolemodulesService.remove(queryWrapper);

        //2.给指定的角色批量添加数据
        List<Rolemodules> list = new ArrayList<>();
        String[] arr = mids.split(",");
        for (String s : arr){
            list.add(new Rolemodules(0,rid,Integer.valueOf(s)));
        }

        boolean res = iRolemodulesService.saveBatch(list);
        if(res) {
            return new Result(0,"设置成功");
        }else {
            return new Result(1,"设置失败");
        }
    }

}
